package com.suse.service.community.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.suse.common.base.model.entity.Page;
import com.suse.service.community.constant.EntityTypeConstant;
import com.suse.service.community.entity.DiscussPost;
import com.suse.service.community.service.ElasticsearchService;
import com.suse.service.community.service.LikeService;
import com.suse.service.community.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 搜索前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-04 15:07
 */
@Controller
public class SearchController {

    @Resource
    private ElasticsearchService elasticsearchService;

    @Resource
    private UserService userService;

    @Resource
    private LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) {
        // 分页信息
        page.setPath("/search?keyword=" + keyword);
        // 讨论发布列表
        List<DiscussPost> discussPostList = elasticsearchService.searchDiscussPost(keyword, page);
        // 讨论发布VO列表
        List<Map<String, Object>> discussPostVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(discussPostList)) {
            for (DiscussPost post : discussPostList) {
                Map<String, Object> discussPostVo = new HashMap<>();
                // 帖子
                discussPostVo.put("post",post);
                // 发帖人
                discussPostVo.put("user",userService.getUserById(post.getUserId()));
                // 点赞数
                discussPostVo.put("likeCount",likeService.getEntityLikeCount(EntityTypeConstant.POST,post.getId()));
                discussPostVoList.add(discussPostVo);
            }
        }
        model.addAttribute("keyword",keyword);
        model.addAttribute("discussPostList",discussPostVoList);
        return "site/search";
    }

}
